<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no" />
    <title>MyCAT EYE-mycat setting Schema</title>
    <link href="bootstrap-3.3.5-dist/css/bootstrap.min.css" title="" rel="stylesheet" />
    <link href="../assets/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="css/jquery.mloading.css" />
    <link title="blue" href="css/dermadefault.css" rel="stylesheet" type="text/css" />
    <link title="green" href="css/dermagreen.css" rel="stylesheet" type="text/css" disabled="disabled" />
    <link title="orange" href="css/dermaorange.css" rel="stylesheet" type="text/css" disabled="disabled" />
    <link href="css/templatecss.css" rel="stylesheet" title="" type="text/css" />
    <link href="css/jquery.dataTables.min.css" rel="stylesheet" title="" type="text/css" />
    <link title="" href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<nav class="nav navbar-default navbar-mystyle navbar-fixed-top">
    <div class="navbar-header">
        <button class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand mystyle-brand"><span class="glyphicon glyphicon-home"></span></a>
    </div>
    <div class="collapse navbar-collapse">
        <ul class="nav navbar-nav">
            <li class="">
                <a class="mystyle-color" href="../index.html">MyCAT EYE&nbsp;&nbsp;&nbsp;</a>
            </li>
        </ul>
        <ul class="nav navbar-nav pull-right">
            <li class="dropdown" style="min-width:165px;">
                <a href="#" class="dropdown-toggle mystyle-color" data-toggle="dropdown">&nbsp;当前Mysql：
                    <span id="currentServerId" data-value="">所属节点</span>
                    <span class="caret"></span>
                </a>
                <ul class="dropdown-menu" id="ulNodeList">
                    <li class="dropdown-item"><a class="dropdown-item" data-name="所属节点" data-value="">所属节点</a></li>
                </ul>
            </li>
            <li class="dropdown">
                <a href="#" class="dropdown-toggle mystyle-color" data-toggle="dropdown">&nbsp;当前Mycat：
                    <span id="mycat_server" data-value="">所属节点</span>
                    <span class="caret"></span>
                </a>
                <ul class="dropdown-menu" id="ulMycatList">
                    <li class="dropdown-item"><a class="dropdown-item" data-name="所属节点" data-value="">所属节点</a></li>
                </ul>
            </li>
            <li class="dropdown li-border">
                <a href="#" class="dropdown-toggle mystyle-color" data-toggle="dropdown">
                    &nbsp;<span id="login_admin"></span>
                    <span class="caret"></span>
                </a>
                <ul class="dropdown-menu">
                    <li><a href="javascript:void(0)" id="modifyPassword">修改密码</a></li>
                    <li><a href="javascript:void(0)" id="logout">退出</a></li>
                </ul>
            </li>
        </ul>
    </div>

</nav>

<div class="down-main">
    <div class="left-main left-full">
        <div class="sidebar-fold">
            <span class="glyphicon glyphicon-menu-hamburger"></span>
        </div>
        <div class="subNavBox">
            <div class="sBox">
                <div class="subNav sublist-down">
                    <span class="title-icon fa fa-angle-down"></span><span
                        class="sublist-title">常用功能</span>
                </div>
                <ul class="navContent">
                    <li>
                        <div class="showtitle">
                            <img src="img/leftimg.png" />控制台
                        </div>
                        <a href="dashboard.html">
                            <span class="sublist-icon fa fa-dashboard"></span>
                            <span class="sub-title">控制台</span>
                        </a>
                    </li>
                    <li>
                        <div class="showtitle">
                            <img src="img/leftimg.png" />变量管理
                        </div>
                        <a href="var-manage.html">
                            <span class="sublist-icon fa fa-dot-circle-o"></span>
                            <span class="sub-title">变量管理</span>
                        </a>
                    </li>
                </ul>
            </div>
            <div class="sBox">
                <div class="subNav sublist-down">
                    <span class="title-icon fa fa-angle-down"></span>
                    <span class="sublist-title">InnoDB引擎</span>
                </div>
                <ul class="navContent">
                    <li>
                        <div class="showtitle">
                            <img src="img/leftimg.png" />基本状态
                        </div>
                        <a href="innodb-status.html">
                            <span class="sublist-icon fa fa-heartbeat"></span>
                            <span class="sub-title">基本状态</span>
                        </a>
                    </li>
                    <li>
                        <div class="showtitle">
                            <img src="img/leftimg.png" />事务查看
                        </div>
                        <a href="innodb-trx.html">
                            <span class="sublist-icon fa fa-retweet"></span>
                            <span class="sub-title">事务查看</span>
                        </a>
                    </li>
                    <li>
                        <div class="showtitle">
                            <img src="img/leftimg.png" />锁等待信息
                        </div>
                        <a href="innodb-lockwaits.html">
                            <span class="sublist-icon fa fa-lock"></span>
                            <span class="sub-title">锁等待信息</span></a>
                    </li>
                </ul>
            </div>
            <div class="sBox">
                <div class="subNav sublist-down">
                    <span class="title-icon fa fa-angle-down"></span>
                    <span class="sublist-title">Mysql管理</span>
                </div>
                <ul class="navContent">
                    <li>
                        <div class="showtitle">
                            <img src="img/leftimg.png" />Mysql集群管理
                        </div>
                        <a href="cluster-manage.html">
                            <span class="sublist-icon fa fa-list"></span>
                            <span class="sub-title">Mysql集群管理</span>
                        </a>
                    </li>
                    <li>
                        <div class="showtitle">
                            <img src="img/leftimg.png" />Mysql节点管理
                        </div>
                        <a href="node-manage.html">
                            <span class="sublist-icon fa fa-cubes"></span>
                            <span class="sub-title">Mysql节点管理</span>
                        </a>
                    </li>
                </ul>
            </div>
            <div class="sBox">
                <div class="subNav sublist-down">
                    <span class="title-icon fa fa-angle-down"></span>
                    <span class="sublist-title">Mycat管理</span>
                </div>
                <ul class="navContent">
                    <li class="active">
                        <div class="showtitle">
                            <img src="img/leftimg.png" />Mycat集群管理
                        </div>
                        <a href="mycat-cluster.html">
                            <span class="sublist-icon fa fa-database"></span>
                            <span class="sub-title">Mycat集群管理</span>
                        </a>
                    </li>
                    <li>
                        <div class="showtitle">
                            <img src="img/leftimg.png" />Mycat节点管理
                        </div>
                        <a href="mycat-node.html">
                            <span class="sublist-icon fa fa-cube"></span>
                            <span class="sub-title">Mycat节点管理</span>
                        </a>
                    </li>
                </ul>
            </div>
            <div class="sBox">
                <div class="subNav sublist-down">
                    <span class="title-icon fa fa-angle-down"></span>
                    <span class="sublist-title">设置</span>
                </div>
                <ul class="navContent">
                    <li>
                        <div class="showtitle">
                            <img src="img/leftimg.png" />系统属性
                        </div>
                        <a href="mycat-setting-myid.html">
                            <span class="sublist-icon fa fa-ban"></span>
                            <span class="sub-title">系统属性</span>
                        </a>
                    </li>
                    <li >
                        <div class="showtitle">
                            <img src="img/leftimg.png" />参数配置
                        </div>
                        <a href="mycat-setting-server.html">
                            <span class="sublist-icon fa fa-list-alt"></span>
                            <span class="sub-title">参数配置</span>
                        </a>
                    </li>
                    <li>
                        <div class="showtitle">
                            <img src="img/leftimg.png" />数据源设置
                        </div>
                        <a href="mycat-setting-mycat-schema.html">
                            <span class="sublist-icon fa fa-cloud"></span>
                            <span class="sub-title">数据源设置</span>
                        </a>
                    </li>
                    <li>
                        <div class="showtitle">
                            <img src="img/leftimg.png" />分片设置
                        </div>
                        <a href="mycat-setting-rule.html">
                            <span class="sublist-icon fa fa-share"></span>
                            <span class="sub-title">分片设置</span>
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </div>

    <div class="right-product right-full">
        <div class="container-fluid">
            <div class="info-center">
                <div class="page-header">
                    <div class="pull-left">
                        <h4>参数配置</h4>
                    </div>
                    <div class="pull-right mt10">
                        ...
                    </div>
                </div>

                <div class="panel panel-default panel-intro table-margin">
                    <div class="panel-body">
                        <div class="tab-content">
                            <div class="tab-pane fade active in" id="one">
                                <div class="widget-body no-padding" id="mycatSchemaContainer">
                                    <div class=""><h4><span>schema</span></h4></div>
                                    <div class="manage-detail">
                                        <div class="margin-tb manage-detail-con clearfix">
                                            <a class="h5 custom pull-left " id="btnAddSchema" href="javascript:void(0);">新增schema</a>
                                            <a class="h5 custom pull-right margin-min-15" id="getSchemaFromZk" href="javascript:void(0);">从zk获取配置</a>
                                            <a class="h5 custom pull-right margin-min-15" id="saveLocalSchema" href="javascript:void(0);">保存后端数据库</a>
                                            <a class="h5 custom pull-right margin-min-15" id="saveSchema" href="javascript:void(0);">保存到ZK</a>
                                        </div>
                                    </div>
                                    <table class="table table-striped" id="mySchemaModalContainer">
                                        <thead>
                                        <tr>
                                            <th>名称</th>
                                            <th>checkSQLschema</th>
                                            <th>sqlMaxLimit</th>
                                            <th>dataNode</th>
                                            <th>操作</th>
                                        </tr>
                                        </thead>
                                    </table>
                                </div>

                                <div class="" id="container" style="display: none">
                                    <div class=""><h4><span>数据源</span></h4></div>
                                    <div class="manage-detail">
                                        <div class="margin-tb manage-detail-con clearfix">
                                            <a class="h5 custom pull-left" id="btnAddSchemaTable" href="javascript:;">新增table</a>
                                        </div>
                                    </div>
                                    <table class="table table-striped" id="mySchemaTableContainer">
                                        <thead>
                                            <tr>
                                                <th>名称</th>
                                                <th>type</th>
                                                <th>rule</th>
                                                <th>dataNode</th>
                                                <th>primaryKey</th>
                                                <th>自增长</th>
                                                <th>分表</th>
                                                <th>添加limit</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<div class="modal fade myModal" id="myModal" tabindex="0" role="dialog" aria-labelledby="myModal" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="myHostLabel"><span>新增</span>schema</h5>
                <button type="button" class="fa fa-close close" data-dismiss="modal" aria-label="Close">
                </button>
            </div>
            <div class="">
                <div class="form-horizontal" id="editSchemaModalContainer">

                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-info btn-submit editOrAddSchema">提交</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade myTableModal" id="myTableModal" tabindex="0" role="dialog" aria-labelledby="myTableModal" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="myTableModalLabel"><span>新增</span>table</h5>
                <button type="button" class="fa fa-close close" data-dismiss="modal" aria-label="Close">
                </button>
            </div>
            <div class="modal-body">
                <div class="form-horizontal" id="editTableModalContainer">

                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-info btn-submit editOrAddTable" id="editOrAddTable">提交</button>
            </div>
        </div>
    </div>
</div>


<div id="childTableContainer" style="display: none">
    <div class="" id="" >
        <div class=""><h4><span id="childTableContainerTitle">childTableList</span></h4> </div>
        <div class="manage-detail">
            <div class="margin-tb manage-detail-con clearfix">
                <a class="h5 custom pull-left" id="btnAddChildTable" href="javascript:;">新增Childtable</a>
                <a class="h5 custom pull-right" id="backChildTable" href="javascript:void(0);">返回</a>
            </div>
        </div>
        <table class="table table-striped" id="myChildTableContainer">
            <thead>
            <tr>
                <th>名称</th>
                <th>joinKey</th>
                <th>parentKey</th>
                <th>primaryKey</th>
                <th>添加limit</th>
                <th>操作</th>
            </tr>
            </thead>
        </table>
    </div>

</div>
<div style="display: none" id="editChildTableContainer">
</div>
<!-- javascript -->
<script src="script/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="script/jquery.cookie.js" type="text/javascript"></script>
<script src="bootstrap-3.3.5-dist/js/bootstrap.min.js" type="text/javascript"></script>
<script src="script/bootbox.min.js" type="text/javascript"></script>
<script src="script/jquery.dataTables.min.js"></script>
<!-- loading效果 -->
<script src="script/jquery.mloading.js"></script>
<!-- 自定义javascript -->
<script src="script/custom/menu.js"></script>
<script src="script/custom/login-auth.js"></script>
<script src="script/custom/modify-password.js"></script>
<script src="script/custom/current-node.js"></script>
<script src="../assets/js/utils.js"></script>
<script src="script/juicer-min.js"></script>
<script src="script/layer/layer.js"></script>
<!-- Schema编辑模板模板 -->
<script id="tmpl" type="text/template">
    <div class="form-horizontal">
        <div class="form-group mt10">
            <label class="col-sm-3 control-label">name：</label>
            <div class="col-sm-9">
                <input class="form-control" type="text" value="${name}" name="name" data-old-name="${name}"/>
            </div>
        </div>
        <div class="form-group mt10">
            <label class="col-sm-3 control-label">checkSQLschema：</label>
            <div class="col-sm-9">
                <!--<input class="form-control" type="text" value="${checkSQLschema}" name="checkSQLschema" />-->
                <label class="custom-control custom-radio">
                <input name="checkSQLschema" value="true" type="radio" class="custom-control-input " ${true==checkSQLschema?"checked":""} ${(undefined==checkSQLschema)?"checked":""}>
                <span class="custom-control-indicator"></span>
                <span class="custom-control-description">是</span>
                </label>
                <label class="custom-control custom-radio">
                    <input name="checkSQLschema" value="false" type="radio" class="custom-control-input " ${(false==checkSQLschema)?"checked":""}  >
                    <span class="custom-control-indicator"></span>
                    <span class="custom-control-description">否</span>
                </label>
            </div>
        </div>

        <div class="form-group mt10">
            <label class="col-sm-3 control-label">sqlMaxLimit：</label>
            <div class="col-sm-9">
                <input class="form-control" type="text" value="${sqlMaxLimit}" name="sqlMaxLimit" />
            </div>

         </div>
        <div class="form-group mt10">
            <label class="col-sm-3 control-label">dataNode：</label>
            <div class="col-sm-9">
                <input class="form-control" type="text" value="${dataNode}" name="dataNode" />
            </div>
        </div>
    </div>

</script>



<!-- Schema的table模板 -->
<script id="tableTmpl" type="text/template">
    <div class="form-horizontal">
        <div class="form-group mt10">
            <label class="col-sm-3 control-label">name：</label>
            <div class="col-sm-9">
                <input class="form-control" type="text" value="${name}" name="name" data-old-name="${name}" data-schema-name="${schemaName}"/>
            </div>
        </div>

        <!-- 判断是否globalTable -->
        <div class="form-group mt10">
            <label class="col-sm-3 control-label">全局表：</label>
            <div class="col-sm-9">
                <label class="custom-control custom-radio">
                    <input name="type" value="global" type="radio" class="custom-control-input loadZk" ${"global"==type?"checked":""}>
                    <span class="custom-control-indicator"></span>
                    <span class="custom-control-description">是</span>
                </label>
                <label class="custom-control custom-radio">
                    <input name="type" value="" type="radio" class="custom-control-input loadZk" ${"global"!=type?"checked":""}>
                    <span class="custom-control-indicator"></span>
                    <span class="custom-control-description">否</span>
                </label>
            </div>
        </div>

        <div class="form-group mt10 ruleDiv"  >
            <label class="col-sm-3 control-label">rule：</label>
            <div class="col-sm-9">
                <input class="form-control" type="text" value="${rule}" name="rule" />
            </div>
        </div>
        <div class="form-group mt10">
            <label class="col-sm-3 control-label">dataNode：</label>
            <div class="col-sm-9">
                <input class="form-control" type="text" value="${dataNode}" name="dataNode" />
            </div>
        </div>

        <div class="form-group mt10 "  >
            <label class="col-sm-3 control-label">primaryKey：</label>
            <div class="col-sm-9">
                <input class="form-control" type="text" value="${primaryKey}" name="primaryKey" />
            </div>
        </div>

        <!-- 判断是否globalTable -->
        <div class="form-group mt10">
            <label class="col-sm-3 control-label">自增长：</label>
            <div class="col-sm-9">
                <label class="custom-control custom-radio">
                    <input name="autoIncrement" value="true" type="radio" class="custom-control-input " ${true==autoIncrement?"checked":""}>
                    <span class="custom-control-indicator"></span>
                    <span class="custom-control-description">是</span>
                </label>
                <label class="custom-control custom-radio">
                    <input name="autoIncrement" value="false" type="radio" class="custom-control-input " ${(false==autoIncrement)?"checked":""}  ${(undefined==autoIncrement)?"checked":""}>
                    <span class="custom-control-indicator"></span>
                    <span class="custom-control-description">否</span>
                </label>
            </div>
        </div>
        <div class="form-group mt10 ruleDiv "  >
            <label class="col-sm-3 control-label">subTables：</label>
            <div class="col-sm-9">
                <input class="form-control" type="text" value="${subTables}" name="subTables" />
            </div>
        </div>
        <!-- 判断是否needAddLimit-->
        <div class="form-group mt10">
            <label class="col-sm-3 control-label">添加limit：</label>
            <div class="col-sm-9">
                <label class="custom-control custom-radio">
                    <input name="needAddLimit" value="true" type="radio" class="custom-control-input " ${true==needAddLimit?"checked":""} ${(undefined==needAddLimit)?"checked":""}>
                    <span class="custom-control-indicator"></span>
                    <span class="custom-control-description">是</span>
                </label>
                <label class="custom-control custom-radio">
                    <input name="needAddLimit" value="false" type="radio" class="custom-control-input " ${(false==needAddLimit)?"checked":""}  >
                    <span class="custom-control-indicator"></span>
                    <span class="custom-control-description">否</span>
                </label>
            </div>
        </div>
    </div>
</script>


<!-- Schema的childTable模板 -->
<script id="childTableTmpl" type="text/template">
    <!--<div class="modal-dialog" role="document">-->
        <div class="">
            <div class="modal-body">
                <div class="form-horizontal" >
                    <div class="form-horizontal">
                        <!---->
                        <div class="form-group mt10">
                            <label class="col-sm-3 control-label">name：</label>
                            <div class="col-sm-9">
                                <input class="form-control" type="text" value="${name}" name="name" data-old-name="${name}" />
                            </div>
                        </div>

                        <!-- 判断是否globalTable -->
                        <div class="form-group mt10">
                            <label class="col-sm-3 control-label">是否自增长：</label>
                            <div class="col-sm-9">
                                <label class="custom-control custom-radio">
                                    <input name="autoIncrement" value="0" type="radio" class="custom-control-input loadZk" ${"true"==autoIncrement?"checked":""}>
                                    <span class="custom-control-indicator"></span>
                                    <span class="custom-control-description">是</span>
                                </label>
                                <label class="custom-control custom-radio">
                                    <input name="autoIncrement" value="1" type="radio" class="custom-control-input loadZk" ${"autoIncrement"!=autoIncrement?"checked":""}>
                                    <span class="custom-control-indicator"></span>
                                    <span class="custom-control-description">否</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group mt10">
                        <label class="col-sm-3 control-label">joinKey：</label>
                        <div class="col-sm-9">
                            <input class="form-control" type="text" value="${joinKey}" name="joinKey" />
                        </div>
                    </div>
                    <div class="form-group mt10 "  >
                        <label class="col-sm-3 control-label">parentKey：</label>
                        <div class="col-sm-9">
                            <input class="form-control" type="text" value="${parentKey}" name="parentKey" />
                        </div>
                    </div>
                    <div class="form-group mt10 "  >
                        <label class="col-sm-3 control-label">primaryKey：</label>
                        <div class="col-sm-9">
                            <input class="form-control" type="text" value="${primaryKey}" name="primaryKey" />
                        </div>
                    </div>
                    <!-- 判断是否needAddLimit-->
                    <div class="form-group mt10">
                        <label class="col-sm-3 control-label">添加limit：</label>
                        <div class="col-sm-9">
                            <label class="custom-control custom-radio">
                                <input name="needAddLimit" value="true" type="radio" class="custom-control-input " ${true==needAddLimit?"checked":""}>
                                <span class="custom-control-indicator"></span>
                                <span class="custom-control-description">是</span>
                            </label>
                            <label class="custom-control custom-radio">
                                <input name="needAddLimit" value="false" type="radio" class="custom-control-input " ${(false==needAddLimit)?"checked":""}  ${(undefined==needAddLimit)?"checked":""}>
                                <span class="custom-control-indicator"></span>
                                <span class="custom-control-description">否</span>
                            </label>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary cancelChildTable" id="cancelChildTable" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-info btn-submit editOrAddTable" id="editOrAddChildTable">提交</button>
            </div>
        </div>
    <!--</div>-->
</script>

<script type="text/javascript">
    var table;
    var schemaMap ={};

    layer.config({
        path: '/script/layer/' //layer.js所在的目录，可以是绝对目录，也可以是相对目录
    });
    function fetchData(forceFromZk) {
        if(table){
            for(var attr in schemaMap) {
                delete schemaMap[attr];
            }
            $('#container').hide();
            table.destroy();
        }
        //http://www.datatables.club/example/data_sources/js_array.html
        table = $('#mySchemaModalContainer').DataTable({
            'oLanguage': dtb.oLanguage,
            'ajax': {
                "url":  String.format("/mycat/zk/{0}/schema/schema",getParameter("cluster")) ,
                "data":{
                    forceFromZk : forceFromZk?1:0
                },
                "dataSrc": function ( json ) {
                    if(json.code == 200){
                        if(typeof  json.data == "string"){
                            return JSON.parse(json.data);
                        }
                        return json.data;
                    } else{
                        layer.msg("请求失败！");
                    }
                    return [];
                }
            } ,
            'columns': [
                {'data': 'name'},
                {'data': 'checkSQLschema'},
                {'data': 'sqlMaxLimit'},
                {'data': 'dataNode'}
            ],
            'columnDefs': [
                {
                    'render': function(data,type,row){
                        schemaMap[row["name"]] = row;
                        return '<a href="javascript:void(0)" class="btn-del text-info delSchema" data-name="'+row['name']+'"><i class="fa fa-trash-o"></i> 删除</a> ' +
                            '| <a href="javascript:void(0)" class="btn-edit text-info edit editSchema" data-name="'+row['name']+'"><i class="fa fa-edit"></i> 编辑</a>'
                           + '| <a href="javascript:void(0)" class="btn-edit text-info edit editSchemaTableList" data-name="'+row['name']+'"><i class="fa fa-edit"></i> 编辑tableList</a>' +'';
                    },
                    'targets': 4
                },
                {"defaultContent": "",
                    "targets": "_all"}
            ],
            "drawCallback": function( settings ) {
            }
        });
    }
    fetchData();

    var myModal = $("#myModal");
    //新增 Schema
    $("#mycatSchemaContainer").on("click",".delSchema",function () {

        if(confirm("确定删除吗？")) {
            //界面上删除一行shema的记录
            $('#mySchemaModalContainer').DataTable().row($(this).parents('tr')).remove().draw();
            delSchema($(this).data("name"),"del");
            layer.msg("删除成功");
        }
    });

    //todo 保存后端数据库
    $("#btnAddSchema").on("click", function () {
        addOrEditSchema($(this),"add");
    })
    //saveLocalSchema
    //saveSchema
    $("#saveSchema").on("click", function () {
        var list = [];
        for(var schemaName in schemaMap) {
            list.push(schemaMap[schemaName]);
        }
        console.log(JSON.stringify(list));
        saveSchemaToRemote(String.format("/mycat/zk/{0}/schema/schema",getUrlParam("cluster")), list);
    });
    $("#saveLocalSchema").on("click", function () {
        var list = [];
        for(var schemaName in schemaMap) {
            list.push(schemaMap[schemaName]);
        }
        console.log(JSON.stringify(list));
        saveSchemaToRemote(String.format("/mycat/zk/{0}/schema/updateLocalSchema",getUrlParam("cluster")), list);
    })
    //getSchemaFromZk
    $("#getSchemaFromZk").on("click", function () {
       fetchData(true);
    })
    var saveSchemaToRemote = function (url, data) {
        $.ajax({
            url: url,
            method: 'post',
            data:{
                body : JSON.stringify(data)
            },
            success: function(res, status,jqxhr){
                if(res.code && res.code==200){
                    layer.msg("保存成功");
                    //fetchData();
                }else{
                    notifi.error('Error: '+res.message)
                }
            },
            error: function(err,status){
                console.log(err);
                notifi.error(err || err.message? err.message:'');
            }
        });
    }
    $("#mycatSchemaContainer").on("click",".editSchema", function () {
        addOrEditSchema($(this),"edit");
    });
    //显示编辑的对话框
    var addOrEditSchema = function (obj, type) {
        var  json = {type: type};
        if(type == "edit"){
            var name = obj.data("name");
            json = schemaMap[name] ;
            json.type = type;
        }
        var html = juicer($("#tmpl").html(), json);
        $("#editSchemaModalContainer").html(html);
        myModal.modal('show');
    }

    //封装数据结构
    var getSchema = function (dataNodeName) {
        return schemaMap[dataNodeName];
    }
    //添加一个Schema
    var addSchema = function (oldDataNodeName, json) {
        if(oldDataNodeName == "") {
            schemaMap[json["name"]] = json;
        } else {
            var obj = schemaMap[oldDataNodeName];
            delete schemaMap[oldDataNodeName];
            schemaMap[json["name"]] = $.extend(obj, json);
        }
        return schemaMap[json["name"]];
    };

    //删除schema列表.
    var delSchema = function (dataNodeName) {
        schemaMap[dataNodeName] = null;
    };
    //保存新增修改的schema数据.
    $(".editOrAddSchema").click(function () {
        var obj  = {};
        $("#editSchemaModalContainer").find("input").each(function () {
            var name = $(this).attr("name");
            var val = $(this).val();
            obj[name] = val;
        });
        var checkSQLschema = $("#editSchemaModalContainer").find("input[name=checkSQLschema]:checked").val() == "true" ?true: false;
        obj["checkSQLschema"] = checkSQLschema;
        var oldSchema =  $("#editSchemaModalContainer").find("input[name='name']").data("old-name");
        addSchema(oldSchema, obj);
        if(oldSchema !== "") {
            $('#mySchemaModalContainer').DataTable().row($("#mycatSchemaContainer").find("a[data-name='"+oldSchema+"']").parents("tr")).data(getSchema(obj["name"])).draw();
        }else {
            $('#mySchemaModalContainer').DataTable().row.add(getSchema(obj["name"])).draw();

        }
//$('#mySchemaModalContainer').DataTable().row($("#editSchemaModalContainer").find("input[name='name']").parents('tr')).row().data({checkSQLschema: "false", sqlMaxLimit: "1000006", name: "MYTESTDB", table: Array(6), type: "edit"}).draw(false);
        myModal.modal('hide');
    });

    var getTable = function (schemaName, tableName) {
        var schemaJson = getSchema(schemaName);
        for(var i = 0 ; i < schemaJson.table.length; i++) {
            if(schemaJson.table[i].name == tableName) {
                return schemaJson.table[i];
            }
        }
    }
    
    var setTable = function (schemaName, oldTableName, tableJson) {
        var schemaJson = getSchema(schemaName);
        for(var i = 0 ; i < schemaJson.table.length; i++) {
            if(schemaJson.table[i].name == oldTableName) {
                 schemaJson.table[i] = $.extend(schemaJson.table[i],  tableJson);
                delEmptyAttr(schemaJson.table[i]);
                 return;
            }
        }
        delEmptyAttr(tableJson);
        schemaJson.table.push(tableJson);
    }
    var delTable = function (schemaName, tableName) {
        var schemaJson = getSchema(schemaName);
        for(var i = 0 ; i < schemaJson.table.length; i++) {
            if(schemaJson.table[i].name == tableName) {
                schemaJson.table.remove(schemaJson.table[i]) ;
                return;
            }
        }
    }



    //编辑tableList
    $("#mycatSchemaContainer").on("click",".editSchemaTableList", function () {
        var dataNodeName =  $(this).data("name");
        var schema = getSchema(dataNodeName);
        var tableList = schema.table;
        if(!tableList) {
            tableList == [];
            schema.table =[];
        }
        $('#container').show();
        $('#mySchemaTableContainer').dataTable().fnDestroy();
        $('#mySchemaTableContainer').attr("schemaName",schema.name);
        $('#mySchemaTableContainer').DataTable({
            'oLanguage': dtb.oLanguage,
            "data": tableList,
            'columns': [
                {'data': 'name',"width":"60px"},
                {'data': 'type',"width":"30px"},
                {'data': 'rule'},
                {'data': 'dataNode',"width":"130px"},
                {'data': 'primaryKey',"width":"30px"},
                {'data': 'autoIncrement',"width":"30px"},
                {'data': 'subTables'},
                {'data': 'needAddLimit',"width":"30px"}

            ],
            'columnDefs': [
                {
                    'render': function(data,type,row){
                        return '<a href="javascript:void(0)" class="btn-del text-info delTable" data-name="'+row['name']+'"><i class="fa fa-trash-o"></i> 删除</a> ' +
                            '| <a href="javascript:void(0)" class="btn-edit text-info edit editTable" data-name="'+row['name']+'"><i class="fa fa-edit"></i> 编辑</a>'
                            + '| <a href="javascript:void(0)" class="btn-edit text-info edit editChildTableList" data-name="'+row['name']+'"><i class="fa fa-edit"></i> 编辑childTable</a>' +'';
                    },
                    'targets': 8,
                    "width":"130px"
                },
                {"defaultContent": "",
                    "targets": "_all"}
            ],
            "drawCallback": function( settings ) {
            }
        });
    });
    $('#mySchemaTableContainer').on("click",".delTable",function () {

        if(confirm("确定删除吗？")) {
            //界面上删除一行shema的记录
            var schemaName = $('#mySchemaTableContainer').attr("schemaName");
            var tableName = $(this).data("name");
            delTable(schemaName, tableName);
            $('#mySchemaTableContainer').DataTable().row($(this).parents('tr')).remove().draw();

        }
    });
    
    $("#btnAddSchemaTable").bind("click",function () {
        var html = $("#tableTmpl").html();
        var schemaName = $('#mySchemaTableContainer').attr("schemaName");
        var json = $.extend({schemaName: schemaName}, {} )
        $("#editTableModalContainer").html(juicer(html, json));
        $("#myTableModal").modal("show");


    });
    var checkIfGlobal = function (isClear) {
        var type = $("#editTableModalContainer").find("input[name=type]:checked").val();
        if(type == ""){
            $(".ruleDiv").show();
        } else{
            $(".ruleDiv").hide();
        }
        if(isClear){
            $(".ruleDiv").find("input[name=rule],input[name=subTables]").val("");
        }
    }
    $("#editTableModalContainer").on("click","input[name=type]",function () {
        checkIfGlobal(true);
    });

    $("#container").on("click",".editTable",function () {
        var html = $("#tableTmpl").html();
        var tableName = $(this).data("name");
        var schemaName = $('#mySchemaTableContainer').attr("schemaName");
        var tableJson = getTable(schemaName, tableName);
        var json = $.extend({schemaName: schemaName}, tableJson )
        $("#editTableModalContainer").html(juicer(html, json));
//        debugger
        checkIfGlobal(false);
        $("#myTableModal").modal("show");

        //tableTmpl
    });
    //
    //保存新增修改的table数据.
    $(".editOrAddTable").click(function () {
        var obj = {};
        var container = $("#editTableModalContainer");
        container.find("input").each(function () {
            var name = $(this).attr("name");
            var val = $(this).val();
            obj[name] = val;
        });
        var type = $("#editTableModalContainer").find("input[name=type]:checked").val();
        obj["type"] = type;
        var autoIncrement = $("#editTableModalContainer").find("input[name=autoIncrement]:checked").val() == "true" ?true: false;
        obj["autoIncrement"] = autoIncrement;
        var needAddLimit = $("#editTableModalContainer").find("input[name=needAddLimit]:checked").val() == "true" ?true: false;
        obj["needAddLimit"] = needAddLimit;
        var  oldTable= container.find("input[name='name']").data("old-name");
        var schemaName = container.find("input[name='name']").data("schema-name");
        setTable(schemaName, oldTable, obj);
        if (oldTable !== "") {
            //有问题 todo
//            $('#mySchemaModalContainer').DataTable().row().data(getSchema(obj["name"])).draw();

            $('#mySchemaTableContainer').DataTable().row($("#container").find("a[data-name='"+oldTable+"']").parents('tr')).data(getTable(schemaName, obj["name"])).draw();
        } else {
            $('#mySchemaTableContainer').DataTable().row.add(getTable(schemaName, obj["name"])).draw();

        }
        $("#myTableModal").modal("hide");
    });

    $("#container").on("click",".editChildTableList",function () {
        var schemaName = $('#mySchemaTableContainer').attr("schemaName");
        var tableName = $(this).data("name");
        var childNameArrays = [];
        var childList = getChlidList(schemaName, tableName, childNameArrays);
        showChildList (schemaName, tableName, childNameArrays , childList);
    });

    var getChildTableArgs = function ($obj) {
        var schemaName = $('#childTableContainer').attr("schemaName");
        var tableName = $("#childTableContainer").attr("tableName");
        var childTableName = $obj.data("name");
        var childNameArraysStr = $('#childTableContainer').attr("childNameArrays");
        var childNameArrays = [];
        if(childNameArraysStr !== ""){
            childNameArrays = childNameArraysStr.split(",");
        }
        childNameArrays.push(childTableName);
        return {
            schemaName: schemaName,
            tableName : tableName,
            childTableName: childTableName,
            childNameArrays: childNameArrays
        }
    };

    $('#myChildTableContainer').on("click", ".editChildTableList",function () {
        var childArgs = getChildTableArgs($(this));
        //判断

        var childList = getChlidList(childArgs.schemaName, childArgs.tableName, childArgs.childNameArrays);
        showChildList (childArgs.schemaName, childArgs.tableName, childArgs.childNameArrays , childList);
    });
    var showChildList = function (schemaName, tableName, childNameArrays , childList) {
        if(childList == undefined) childList = [];
        $('#myChildTableContainer').dataTable().fnDestroy();

        $('#childTableContainer').attr("schemaName", schemaName);
        $('#childTableContainer').attr("tableName", tableName);
        $('#childTableContainer').attr("childNameArrays", childNameArrays.join(","));
        $('#childTableContainerTitle').html(String.format("childTableList({0}{1})", tableName , childNameArrays.length>0? "->"+childNameArrays.join("->"):""));
        //
        if(childNameArrays.length ==0){
            $("#backChildTable").hide()
        } else {
            $("#backChildTable").show()
        }
        $('#myChildTableContainer').DataTable({
            'oLanguage': dtb.oLanguage,
            "data": childList,
            'columns': [
                {'data': 'name'},
                {'data': 'joinKey'},
                {'data': 'parentKey'},
                {'data': 'primaryKey'},
                {'data': 'needAddLimit',"width":"30px"}

            ],
            'columnDefs': [
                {
                    'render': function(data,type,row){
                        return '<a href="javascript:void(0)" class="btn-del text-info delChildTable" data-name="'+row['name']+'"><i class="fa fa-trash-o"></i> 删除</a> ' +
                            '| <a href="javascript:void(0)" class="btn-edit text-info edit editChildTable" data-name="'+row['name']+'"><i class="fa fa-edit"></i> 编辑</a>'
                            + '| <a href="javascript:void(0)" class="btn-edit text-info edit editChildTableList" data-name="'+row['name']+'"><i class="fa fa-edit"></i> 编辑childTable</a>' +'';
                    },
                    'targets': 5
                },
                {"defaultContent": "",
                    "targets": "_all"}
            ],
            "drawCallback": function( settings ) {
            }
        });
        layer.open({
            type: 1,
            shade: false,
            scrollbar: false,
            area: ['1020px', '640px'], //宽高
//            title: false, //不显示标题
            content: $('#childTableContainer'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            cancel: function(){
//                layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', {time: 5000, icon:6});
            }
        });
        $("#myChildTableContainer").attr("style","");
    }

    //删除childTable
    $('#myChildTableContainer').on("click",".delChildTable",function () {
        if(confirm("确定删除吗？")) {
            //界面上删除一行shema的记录
            $('#myChildTableContainer').DataTable().row($(this).parents('tr')).remove().draw();
//            delSchema($(this).data("name"),"del");
            var childArgs = getChildTableArgs($(this));
//            var childList = getChlidList(childArgs.schemaName, childArgs.tableName, childArgs.childNameArrays);
            childArgs.childNameArrays.pop();
            delChild(childArgs.schemaName, childArgs.tableName, childArgs.childNameArrays , childArgs.childTableName);
            layer.msg("删除成功");
        }
    })
    var childLayerId = 0;
    //编辑childTable
    $('#myChildTableContainer').on("click",".editChildTable",function () {
        var childArgs = getChildTableArgs($(this));
        childArgs.childNameArrays.pop();
        var childJson = getChild(childArgs.schemaName, childArgs.tableName, childArgs.childNameArrays , childArgs.childTableName);
        var html = $("#childTableTmpl").html();
        $("#editChildTableContainer").html(juicer(html, childJson));
        childLayerId = layer.open({
            type: 1,
            shade: false,
            scrollbar: false,
            area: ['520px', '420px'], //宽高
//            title: false, //不显示标题
            content: $('#editChildTableContainer'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            cancel: function(){
//                layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', {time: 5000, icon:6});
            }
        });
    });
    //editChildTableContainer btnAddChildTable
    $("#childTableContainer").on("click","#btnAddChildTable",function () {
        var html = $("#childTableTmpl").html();
        $("#editChildTableContainer").html(juicer(html, {}));
        childLayerId = layer.open({
            type: 1,
            shade: false,
            scrollbar: false,
            area: ['520px', '420px'], //宽高
            content: $('#editChildTableContainer'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            cancel: function(){
            }
        });
    });
    $("#childTableContainer").on("click","#backChildTable",function () {
        var childArgs = getChildTableArgs($(this));

        if(childArgs.childNameArrays.length == 1){
            layer.msg("已经是最顶级目录了");
            return;
        }

        childArgs.childNameArrays.pop();
        childArgs.childNameArrays.pop();

        var childList = getChlidList(childArgs.schemaName, childArgs.tableName, childArgs.childNameArrays);
        showChildList (childArgs.schemaName, childArgs.tableName, childArgs.childNameArrays , childList);

    });
    //cancelChildTable
    $("#editChildTableContainer").on("click","#cancelChildTable",function () {
        debugger;
        layer.close(childLayerId);
    });
    //保存childTable表
    $("#editChildTableContainer").on("click","#editOrAddChildTable",function () {
        var obj  = {};
        $("#editChildTableContainer").find("input").each(function () {
            var name = $(this).attr("name");
            var val = $(this).val();
            obj[name] = val;
        });
        obj.autoIncrement = $("#editChildTableContainer").find("input[name=autoIncrement]:checked").val() =="0"?false:true;
        obj.needAddLimit = $("#editChildTableContainer").find("input[name=needAddLimit]:checked").val() =="true"?true:false;

        var oldChildName =  $("#editChildTableContainer").find("input[name='name']").data("old-name");
        var childArgs = getChildTableArgs($("#editChildTableContainer").find("input[name='name']"));

        childArgs.childNameArrays.pop();

        //        var childJson = getChild(childArgs.schemaName, childArgs.tableName, childArgs.childNameArrays , oldChildName);
        var childJson = setChild(childArgs.schemaName, childArgs.tableName, childArgs.childNameArrays ,  oldChildName, obj );
        if(oldChildName !== "") {
            $('#myChildTableContainer').DataTable().row($("#myChildTableContainer").find("a[data-name='"+oldChildName+"']").parents("tr")).data(childJson).draw(false);
        }else {
            $('#myChildTableContainer').DataTable().row.add(childJson).draw(false);

        }
        layer.close(childLayerId);
    })

    //获取childList列表
    var getChlidList = function (schemaName, tableName, childNameArrays) {
        var table = getTable(schemaName, tableName);
        if(table.childTable == undefined){
            table.childTable= [];
        }
        if(childNameArrays == undefined) {
            return table.childTable;
        }
        return getChildList2(table.childTable, childNameArrays, 0);
    };

    var getChildList2 = function (list, array, index) {
        if(array.length  == index) {
            return list;
        }
        var name = array[index];
        for(var i = 0 ; i < list.length; i ++) {
            if(name == list[i].name) {
                if(list[i].childTable == undefined){
                    list[i].childTable= [];
                }
                return getChildList2(list[i].childTable, array , ++index);
            }
        }
        return [];
    };

    var getChild = function  (schemaName, tableName, childNameArrays, childName ){
        var childList = getChlidList(schemaName, tableName, childNameArrays) ;

        for(var i = 0 ; i < childList.length; i ++) {
            if(childName == childList[i].name) {
                return childList[i];
            }
        }
        return {};
    };

    var setChild = function  (schemaName, tableName, childNameArrays, oldChildName, childJson ){
        var childList = getChlidList(schemaName, tableName, childNameArrays) ;

        for(var i = 0 ; i < childList.length; i ++) {
            if(oldChildName == childList[i].name) {
                childList[i] = $.extend(childList[i],  childJson);
                delEmptyAttr(childList[i]);
                return childList[i];
            }
        }
        delEmptyAttr(childJson);
        childList.push(childJson);
        return childJson;
    };

    var delChild = function  (schemaName, tableName, childNameArrays, oldChildName ){
        var childList = getChlidList(schemaName, tableName, childNameArrays) ;
        for(var i = 0 ; i < childList.length; i ++) {
            if(oldChildName == childList[i].name) {
                childList.remove(childList[i]);
            }
        }
    };
</script>
</body>
</html>
